package com.qfedu.fy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 *
 * ......................我佛慈悲......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
  *...................佛祖保佑无BUG.......................
 * @author mxj
 @date 2022/6/18 16:40
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    private String[] urls=new String[]{
            ".js",".css",".png",".jpg","login.html","login.do","code.do"
    };
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取请求路径
        HttpServletRequest servletRequest=(HttpServletRequest)request;
        String url=servletRequest.getRequestURI();
        //2.验证是否需要拦截
        boolean r=false;
        //3.遍历循环 验证是否需要拦截处理
        for(String u:urls){
            if(url.endsWith(u)){
                //放行
                r=true;
                break;
            }
        }
        if(r){
            //4.不需要校验，放行
            chain.doFilter(request, response);
        }else {
            //5.校验是否登录
            if(servletRequest.getSession().getAttribute("user")==null){
                //6.拦截,跳转到登录页面
                HttpServletResponse servletResponse=(HttpServletResponse) response;
                servletResponse.sendRedirect("/login.html");
            }else {
                //放行
                chain.doFilter(request, response);
            }
        }
    }
}